<template>
  <div class="users-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统中的所有客户端用户</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="showCreateDialog = true">
          新建用户
        </el-button>
        <el-button :icon="Refresh" @click="loadUsers">刷新</el-button>
        <el-button
          :icon="Delete"
          :disabled="!selectedUsers.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-select
          v-model="statusFilter"
          placeholder="状态筛选"
          clearable
          style="width: 150px; margin-right: 12px"
          @change="loadUsers"
        >
          <el-option label="全部" value="" />
          <el-option label="正常" value="active" />
          <el-option label="禁用" value="disabled" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名/邮箱"
          :prefix-icon="Search"
          clearable
          style="width: 250px"
          @input="handleSearch"
        />
      </div>
    </div>

    <!-- 用户列表 -->
    <el-table
      ref="userTableRef"
      :data="filteredUsers"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      class="user-table"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column label="用户名" min-width="150">
        <template #default="{ row }">
          <div class="user-cell">
            <el-avatar :size="32" :src="row.avatar">
              {{ row.username.charAt(0).toUpperCase() }}
            </el-avatar>
            <span class="username">{{ row.username }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="邮箱" min-width="200" prop="email" />

      <el-table-column label="客户端ID" width="180" prop="client_id" />

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 'active'" type="success" size="small">
            正常
          </el-tag>
          <el-tag v-else type="danger" size="small">禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="在线状态" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.is_online" type="success" size="small" effect="plain">
            <el-icon><Connection /></el-icon>
            在线
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">
            离线
          </el-tag>
        </template>
      </el-table-column>


      <el-table-column label="最后登录" width="180">
        <template #default="{ row }">
          {{ formatTime(row.last_login_at) }}
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.created_at) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button link type="warning" @click="handleResetPassword(row)">
            重置密码
          </el-button>
          <el-button
            link
            :type="row.status === 'active' ? 'warning' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalUsers"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新建/编辑用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="isEdit ? '编辑用户' : '新建用户'"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="客户端ID" prop="client_id">
          <el-input
            v-model="userForm.client_id"
            placeholder="留空自动生成"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="showResetPasswordDialog"
      title="重置密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showResetPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleResetPasswordConfirm">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 发送通知对话框 -->
    <el-dialog
      v-model="showNotificationDialog"
      :title="notificationForm.isBatch ? `向 ${selectedUsers.length} 个用户发送通知` : `向 ${notificationForm.username} 发送通知`"
      width="600px"
    >
      <el-form
        ref="notificationFormRef"
        :model="notificationForm"
        :rules="notificationRules"
        label-width="100px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input
            v-model="notificationForm.title"
            placeholder="请输入通知标题"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入通知内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="通知类型" prop="type">
          <el-radio-group v-model="notificationForm.type">
            <el-radio label="info">普通</el-radio>
            <el-radio label="success">成功</el-radio>
            <el-radio label="warning">警告</el-radio>
            <el-radio label="error">错误</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showNotificationDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSendNotificationConfirm">
          发送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Delete,
  Search,
  Connection
} from '@element-plus/icons-vue'
import axios from '@/api'

// 数据状态
const loading = ref(false)
const users = ref([])
const selectedUsers = ref([])
const searchKeyword = ref('')
const statusFilter = ref('')
let refreshTimer = null // 🔥 自动刷新定时器

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalUsers = ref(0)

// 对话框状态
const showCreateDialog = ref(false)
const showResetPasswordDialog = ref(false)
const showNotificationDialog = ref(false)
const isEdit = ref(false)

// 表单数据
const userForm = reactive({
  id: '',
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  client_id: '',
  status: 'active'
})

const passwordForm = reactive({
  userId: '',
  password: '',
  confirmPassword: ''
})

const notificationForm = reactive({
  userId: null,
  userIds: [],
  username: '',
  title: '',
  content: '',
  type: 'info',
  isBatch: false
})

// 表单引用
const userTableRef = ref()
const userFormRef = ref()
const passwordFormRef = ref()
const notificationFormRef = ref()

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const notificationRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ]
}

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }

  // 关键字搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(
      user =>
        user.username.toLowerCase().includes(keyword) ||
        user.email.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 生命周期
onMounted(() => {
  loadUsers()
  
  // 🔥 自动刷新（每10秒）
  refreshTimer = setInterval(() => {
    loadUsers()
  }, 10000)
})

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/users', {
      params: {
        page: currentPage.value,
        limit: pageSize.value,
        status: statusFilter.value
      }
    })
    
    // 🔥 修复：API返回的数据在 response.data.data 中
    if (response.data.success && response.data.data) {
      users.value = response.data.data.users || []
      totalUsers.value = response.data.data.total || 0
    } else {
      users.value = []
      totalUsers.value = 0
    }
    
    console.log('加载用户列表成功:', users.value.length, '个用户')
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleSearch = () => {
  // 搜索逻辑已在 filteredUsers 计算属性中实现
}

const handleEdit = (user) => {
  isEdit.value = true
  userForm.id = user.id
  userForm.username = user.username
  userForm.email = user.email
  userForm.client_id = user.client_id
  userForm.status = user.status
  showCreateDialog.value = true
}

const handleSubmit = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑用户
          await axios.put(`/api/users/${userForm.id}`, {
            email: userForm.email,
            client_id: userForm.client_id,
            status: userForm.status
          })
          ElMessage.success('更新成功')
        } else {
          // 创建用户
          await axios.post('/api/users', {
            username: userForm.username,
            email: userForm.email,
            password: userForm.password,
            client_id: userForm.client_id || undefined,
            status: userForm.status
          })
          ElMessage.success('创建成功')
        }
        showCreateDialog.value = false
        resetUserForm()
        loadUsers()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.delete(`/api/users/${user.id}`)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedUsers.value.map(u => u.id)
    await axios.post('/api/users/batch-delete', { ids })
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleStatus = async (user) => {
  const newStatus = user.status === 'active' ? 'disabled' : 'active'
  const action = newStatus === 'disabled' ? '禁用' : '启用'

  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.username}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.put(`/api/users/${user.id}/status`, {
      status: newStatus
    })
    ElMessage.success(`${action}成功`)
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}失败:`, error)
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleResetPassword = (user) => {
  passwordForm.userId = user.id
  passwordForm.password = ''
  passwordForm.confirmPassword = ''
  showResetPasswordDialog.value = true
}

const handleResetPasswordConfirm = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.put(`/api/users/${passwordForm.userId}/password`, {
          password: passwordForm.password
        })
        ElMessage.success('密码重置成功')
        showResetPasswordDialog.value = false
      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败')
      }
    }
  })
}

const handleSendNotification = (user) => {
  notificationForm.userId = user.id
  notificationForm.username = user.username
  notificationForm.title = ''
  notificationForm.content = ''
  notificationForm.type = 'info'
  notificationForm.isBatch = false
  showNotificationDialog.value = true
}

const handleBatchNotification = () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请先选择用户')
    return
  }
  notificationForm.userIds = selectedUsers.value.map(u => u.id)
  notificationForm.title = ''
  notificationForm.content = ''
  notificationForm.type = 'info'
  notificationForm.isBatch = true
  showNotificationDialog.value = true
}

const handleSendNotificationConfirm = async () => {
  if (!notificationFormRef.value) return

  await notificationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (notificationForm.isBatch) {
          // 批量发送通知
          await Promise.all(
            notificationForm.userIds.map(userId =>
              axios.post('/api/notifications', {
                user_id: userId,
                title: notificationForm.title,
                content: notificationForm.content,
                type: notificationForm.type
              })
            )
          )
          ElMessage.success(`已向 ${notificationForm.userIds.length} 个用户发送通知`)
        } else {
          // 单个发送通知
          await axios.post('/api/notifications', {
            user_id: notificationForm.userId,
            title: notificationForm.title,
            content: notificationForm.content,
            type: notificationForm.type
          })
          ElMessage.success('通知发送成功')
        }
        showNotificationDialog.value = false
      } catch (error) {
        console.error('发送通知失败:', error)
        ElMessage.error(error.response?.data?.message || '发送通知失败')
      }
    }
  })
}

const resetUserForm = () => {
  isEdit.value = false
  userForm.id = ''
  userForm.username = ''
  userForm.email = ''
  userForm.password = ''
  userForm.confirmPassword = ''
  userForm.client_id = ''
  userForm.status = 'active'
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadUsers()
}

const handlePageChange = (val) => {
  currentPage.value = val
  loadUsers()
}

// 工具函数
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}
</script>

<style scoped>
.users-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.toolbar {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.user-table {
  background: white;
  border-radius: 8px;
}

.user-table :deep(.el-table__header) {
  background: #fafafa;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #333;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
}
</style>
